package com.wonders.framework.web;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.ModelAndView;

import com.wonders.framework.entity.vo.DataGridResult;
import com.wonders.framework.entity.vo.Page;
import com.wonders.framework.util.web.RequestUtil;

/**
 * 基础控制器
 * 
 * @author WuBin
 * 
 */
public class BaseController {

	/**
	 * 异步响应成功
	 * 
	 * @return 响应参数
	 */
	public Map ajaxSuccess() {
		return ajaxSuccess(null);
	}

	/**
	 * 异步响应成功
	 * 
	 * @param object
	 *            响应数据
	 * @return 响应参数
	 */
	public Map ajaxSuccess(Object object) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", true);
		map.put("data", object);
		return map;
	}

	/**
	 * 异步响应失败
	 * 
	 * @param msg
	 *            提示
	 * @return 响应参数
	 */
	public Map ajaxError(String msg) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);
		map.put("type", "tip");
		map.put("msg", msg);
		return map;
	}

	/**
	 * 响应失败
	 * 
	 * @param msg
	 *            提示
	 * @return 响应页面
	 */
	public ModelAndView error(String msg) {
		return new ModelAndView("global/error").addObject("msg", msg);
	}

	/**
	 * 初始化miniui的datagrid的分页查询对象
	 * 
	 * @return 分页对象
	 */
	public Page getDataGridPage() {
		Page page = new Page();
		String pageIndex = (String) RequestUtil.getRequestParam("pageIndex");
		String pageSize = (String) RequestUtil.getRequestParam("pageSize");
		String sortField = (String) RequestUtil.getRequestParam("sortField");
		String sortOrder = (String) RequestUtil.getRequestParam("sortOrder");
		if (StringUtils.isNotBlank(pageIndex)) {
			page.setPageNum(Integer.parseInt(pageIndex) + 1);
		}
		if (StringUtils.isNotBlank(pageSize)) {
			page.setPageSize(Integer.parseInt(pageSize));
		}
		if (StringUtils.isNotBlank(sortField)) {
			page.setSortField(sortField);
		}
		if (StringUtils.isNotBlank(sortOrder)) {
			page.setSortOrder(sortOrder);
		}
		return page;
	}

	/**
	 * 构造miniui的datagrid的分页查询响应对象
	 * 
	 * @param page
	 *            分页查询结果
	 * @return datagrid对象
	 */
	public DataGridResult dataGridResult(Page page) {
		DataGridResult dataGridResult = new DataGridResult();
		dataGridResult.setData(page.getData());
		dataGridResult.setTotal(page.getTotalSize());
		return dataGridResult;
	}

}
